
package com.dhcc.core.config;

import com.dhcc.core.config.properties.MongoDataSourceProperties;
import com.mongodb.MongoClientURI;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;

import java.util.List;
import java.util.stream.Collectors;

@Configuration
public class DynamicMongoTemplatesConfig {

    private static final Logger logger = LoggerFactory.getLogger(DynamicMongoTemplatesConfig.class);
    @Autowired
    private MongoDataSourceProperties mongoDataSourceProperties;

    @Bean
    public List<MongoTemplate> dynamicMongoTemplates() {
        List<String> uris = mongoDataSourceProperties.getUris();
        return uris.stream()
                .map(this::createMongoTemplate)
                .collect(Collectors.toList());
    }

    private MongoTemplate createMongoTemplate(String uri) {
        try {
            MongoClientURI mongoClientURI = new MongoClientURI(uri);
            return new MongoTemplate(new SimpleMongoDbFactory(mongoClientURI));
        } catch (Exception e) {
            // 日志记录异常信息，且避免泄露敏感信息
            logger.error("Failed to create MongoDB template for URI: [REDACTED]", e);
            throw new RuntimeException("Failed to create MongoDB template for URI: " + uri, e);
        }
    }
}